package com.practice.concurrency;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableMain {

	public static void main(String[] args) {
		ExecutorService executor = Executors.newFixedThreadPool(2);

		Callable<String> task = new Callable<String>() {
			@Override
			public String call() throws Exception {
				System.out.println("Start task.");
				for (int i = 0; i < 50; i++) {
					System.out.println("Update progress " + i);	
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("End task.");
				return "OK";
			}
		};
		Callable<Void> blockingTask = new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				System.out.println("Start blocking task.");
				Thread.sleep(5000);
				System.out.println("End blocking task.");
				return null;
			}
		};

		executor.submit(blockingTask);
		Future<String> result = executor.submit(task);

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("Cancel task: " + result.cancel(true));
		try {
			System.out.println("Task is cancelled: " + result.isCancelled());
			System.out.println("Task result: " + result.get());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
